﻿<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="referrer" content="always">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> <!--兼容手机不缩小-->
    <meta http-equiv="x-dns-prefetch-control" content="on">
    <meta name="description" content="光华智能AGV云平台、致力于自动储运新境界。">
    <meta name="format-detection" content="telephone=no">
    <title>光华智能AGV 扫一扫</title>
    <script src="Scripts/jquery-3.4.1.min.js"></script>
    <script src="Scripts/llqrcode.min.js"></script>
    <!--<script src="Scripts/jquery.cookie1.4.1.min.js"></script>-->
    <script src="Scripts/pad.js"></script>
    <link rel="stylesheet" type="text/css" href="Content/Site2.css">
    <script>
    </script>
    <style>
        /*活动菜单*/
        .menu a:nth-child(4),
        .menu a:active {
            background: linear-gradient(#0002, #000f);
            color: #fff;
        }

        /*
        .dis{
            position: relative;
            width: 50%
        }

        .dis *{
            position:absolute;
        }
        */

        video {
            width: 100%;
        }

        .hide {
            display: none;
        }

        #scandata {
            margin-top: 10px;
            width: 100%;
            height: 100px;
            word-break: break-word;
        }

        #prom{
            color: #ff6a00;
        }

        .btnbottom {
            margin: 10px 10px 0px 0px;
        }
    </style>
</head>
<body>
    <div class="split2"></div>

    <div class="dis">
        <video autoplay="autoplay"></video>
        <canvas id="canvas1" width="960" height="960" class="hide"></canvas>
        <img class="hide" src="" alt="" id="img" width="960" height="960" />
    </div>
    <div class="ctrl">
        <div id="prom"></div>
        <textarea id="scandata" title="AGV数据"></textarea>
        <button id="scan" class="btnbottom">重新扫描</button>
        <button id="cameras" class="btnbottom">切换相机</button>
        <button id="picture" class="btnbottom">停止</button>
        <button id="ok" class="btnbottom">确定</button>

        <div class="split"></div>

        <div class="foot">佛山市光华智能设备有限公司</div>
    </div>

    <div class="split2"></div>
</body>
</html>
<script type="text/javascript">
    // https://blog.csdn.net/m0_37693130/article/details/103262794
    // analyticCode.js
    ! function () {
        "use strict";
        let getObjectURL = function (file) {
            let url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        }
        window.analyticCode = {
            getUrl: function (type, elem, fn) {
                let url = null,
                    src = null;
                if (type === 'img-url') {
                    url = elem.src;
                } else if (type === 'file-url' && elem.files.length > 0) {
                    url = getObjectURL(elem.files[0]);
                }
                qrcode.decode(url);
                qrcode.callback = function (imgMsg) {
                    fn(imgMsg, url);
                }
            }
        }
    }();

    var video = document.querySelector('video');
    var audio, audioType;

    var canvas1 = document.getElementById('canvas1');
    var context1 = canvas1.getContext('2d');
    var stream;

    // 兼容不同浏览器内核
    // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }

    // 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
    // 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {

            // 首先，如果有getUserMedia的话，就获得它
            var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

            // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
            if (!getUserMedia) {
                return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
            }

            // 否则，为老的navigator.getUserMedia方法包裹一个Promise
            return new Promise(function (resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
            });
        }
    }

    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

    var exArray = [];
    var curCamera = 0;
    function getVideo() {
        // 遍历摄像头，异步执行
        navigator.mediaDevices.enumerateDevices()
            .then(function (sourceInfos) {
                for (var i = 0; i != sourceInfos.length; ++i) {
                    var sourceInfo = sourceInfos[i];
                    //这里会遍历audio,video，所以要加以区分
                    if (sourceInfo.kind.indexOf('video') >= 0) {
                        exArray.push(sourceInfo.deviceId);
                    }
                }
                if (exArray.length === 0) {
                    $('#prom').text('没有发现摄像头');
                    return;
                }
                else {
                    curCamera = exArray.length - 1;
                    getMedia();
                }
            })
            .catch(function (err) {
                alert(err.name + ": " + err.message);
            });
    }

    function getMedia() {
        if (exArray.length === 0) {
            getVideo();     // 查找摄像头，异步执行，找到后现调用这里。
            return;
        }

        stopCameras();

        // 打开摄像头
        if (navigator.mediaDevices.getUserMedia) {
            //navigator.mediaDevices.getUserMedia({ audio: false, video: true })// 打开后置摄像头  video: { facingMode: { exact: "environment" } }
            navigator.mediaDevices.getUserMedia({ audio: false, video: { width: 960, height: 960, deviceId: exArray[curCamera] } })// 打开后置摄像头  video: { facingMode: { exact: "environment" } }
                .then(function (stream) {
                    var video = document.querySelector('video');
                    // 旧的浏览器可能没有srcObject
                    if ("srcObject" in video) {
                        video.srcObject = stream;
                    } else {
                        // 防止在新的浏览器里使用它，应为它已经不再支持了
                        video.src = window.URL.createObjectURL(stream);
                    }
                })
                .catch(function (err) {
                    errorFunc(err)
                });
        }
        else {
            alert('Native device media streaming (getUserMedia) not supported in this browser.');
        }
    }

    function successFunc(stream) {
        //alert('Succeed to get media!');
        if (video.mozSrcObject !== undefined) {
            //Firefox中，video.mozSrcObject最初为null，而不是未定义的，我们可以靠这个来检测Firefox的支持
            video.mozSrcObject = stream;
        }
        else {
            video.src = window.URL && window.URL.createObjectURL(stream) || stream;
        }
    }
    function errorFunc(e) {
        alert('Error！' + e);
    }

    var imgTiming = null;
    // 将视频帧绘制到Canvas对象上,Canvas每60ms切换帧，形成肉眼视频效果
    function drawVideoAtCanvas(video, context) {
        // 定时进行图片转换成二维码
        imgTiming = window.setInterval(function () {
            context.drawImage(video, 0, 0, 960, 960);
            getImg();
        }, 300);
    }

    // vedio播放时触发，绘制vedio帧图像到canvas
    video.addEventListener('play', function () {
        drawVideoAtCanvas(video, context1);
    }, false);

    // 转化图片
    function getImg() {
        var dataURL = canvas1.toDataURL("image/png");
        // 加载文件
        document.getElementById('img').src = dataURL;
        getUrl(document.getElementById('img'), 'img-url');
    }
    //获取预览图片路径
    var getObjectURL = function (file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

    // 获取二维码地址
    function getUrl(e, param) {
        analyticCode.getUrl(param, e, function (text, imgSrc) {
            // 判断是否解析成功
            if (text == 'error decoding QR Code') {
                if(imgTiming != null)
                    $('#prom').text('请对正二维码');
            } else {
                clearInterval(imgTiming);
                imgTiming = null;
                $('#prom').text('识别成功');
                $('#scandata').text(text);
                stopCameras();
            }
        });
    }

    function stopCameras() {

        // 先暂停，再停止，video中保留原有图像
        video.pause();

        if (video.srcObject && video.srcObject.getTracks) {
            video.srcObject.getTracks().forEach(track => track.stop());
        }
    }

    // 点击扫描二维码
    document.getElementById('scan').onclick = function () {
        $('#scandata').text('');
       getMedia();
    };

    // 切换扫描头
    document.getElementById('cameras').onclick = function () {
        $('#scandata').text('');
        curCamera--;
        if (curCamera < 0)
            curCamera = exArray.length - 1;

        getMedia();
    };

    // 从图片获取二维码
    document.getElementById('picture').onclick = function () {
        stopCameras();
    };

    // 执行相应功能
    document.getElementById('ok').onclick = function () {
        var txt = $('#scandata').text();
        if (txt.indexOf('http') === 0)
            window.open(txt);
    };

    // 登录完成后再打开摄像头，否则登录按钮没反应
    function logged() {
        getMedia();
    }

    // 横屏处理
    function onresize() {

        //$('#prompt').text(window.innerWidth + ', ' + window.innerHeight);
        if (window.innerWidth > window.innerHeight) {
            $('.dis').width('50%');
            $('.ctrl').css({ 'width': 'calc(50% - 10px)',  'margin-left': '10px' });
        }
        else {
            $('.dis').width('100%');
            $('.ctrl').css({ 'width': 'calc(100%)', 'margin-left': '0px' });    // 横屏时中间留点缝
        }
    }

    $(window).resize(
        function () {
            onresize();
        }
    );

    onresize();

</script>